<template>
  <div class="task-flowchart-container">
    <n-card>
      <template #header>
        <div class="header-content">
          <h2>{{ flowchart?.title || '任务流程图' }}</h2>
          <n-select 
            v-model:value="selectedSeason" 
            :options="seasonOptions"
            style="width: 120px"
            @update:value="handleSeasonChange"
          />
        </div>
      </template>
      
      <template #header-extra>
        <n-space>
          <n-button 
            v-if="isEditMode" 
            type="primary"
            @click="handleSave"
            :loading="saving"
          >
            保存
          </n-button>
          <n-button
            v-if="!isEditMode"
            @click="enableEditMode"
          >
            编辑
          </n-button>
          <n-button
            v-if="isEditMode"
            @click="handleCancel"
          >
            取消
          </n-button>
        </n-space>
      </template>

      <div class="flowchart-wrapper" ref="wrapperRef">
        <div v-if="loading" class="loading-overlay">
          <n-spin size="large" />
        </div>
        
        <div v-else-if="!flowchart" class="empty-state">
          <n-empty description="暂无流程图数据" />
        </div>
        
        <div v-else-if="flowNodes.length === 0 && !isEditMode" class="empty-state">
          <n-empty description="流程图为空">
            <template #extra>
              <n-button @click="enableEditMode">开始编辑</n-button>
            </template>
          </n-empty>
        </div>
        
        <div v-else class="flowchart-content">
          <!-- 编辑模式工具栏 - 移动端优化 -->
          <div v-if="isEditMode" class="edit-toolbar" :class="{ 'mobile': isMobile }">
            <n-space>
              <n-button size="small" @click="addNode('task')">
                <template #icon>
                  <n-icon>
                    <svg viewBox="0 0 24 24"><rect x="4" y="6" width="16" height="12" rx="2" fill="currentColor"/></svg>
                  </n-icon>
                </template>
                添加节点
              </n-button>
              <n-divider vertical />
              <span class="edit-tips" v-if="!isMobile">拖动节点移动 | 从节点手柄拖动创建连接 | Delete键删除选中项</span>
              <n-divider vertical v-if="!isMobile" />
              <n-button size="small" type="error" @click="clearAll" :disabled="flowNodes.length === 0">
                清空画布
              </n-button>
            </n-space>
          </div>

          <!-- Vue Flow 流程图 -->
          <VueFlow
            v-model:nodes="flowNodes"
            v-model:edges="flowEdges"
            :default-viewport="{ x: 0, y: 0, zoom: 1 }"
            :min-zoom="0.2"
            :max-zoom="4"
            :connection-mode="isEditMode ? 'loose' : undefined"
            :nodes-draggable="isEditMode"
            :nodes-connectable="isEditMode"
            :edges-updatable="isEditMode"
            :pan-on-drag="!isEditMode"
            :select-nodes-on-drag="false"
            @connect="onConnect"
            @nodes-change="onNodesChange"
            @edges-change="onEdgesChange"
            @node-click="onNodeClick"
            class="vue-flow-container"
          >
            <!-- 背景 -->
            <Background pattern-color="#aaa" :gap="16" />
            
            <!-- 自定义节点模板 - 统一的默认节点 -->
            <template #node-task="{ id, data }">
              <div class="custom-node node-task" :class="{ 'node-completed': getNodeStatus(id) === '已完成' }" @dblclick="() => startEditLabel(id)">
                <div class="node-status-indicator" :class="`status-${getNodeStatus(id)}`" />
                <!-- 顶部：接收连接 -->
                <Handle type="target" :position="Position.Top" :id="`${id}-top`" />
                <!-- 底部：发出连接和接收连接 -->
                <Handle type="source" :position="Position.Bottom" :id="`${id}-bottom`" />
                <Handle type="target" :position="Position.Bottom" :id="`${id}-bottom-target`" />
                <!-- 左右：分支连接和接收连接 -->
                <Handle type="source" :position="Position.Left" :id="`${id}-left`" />
                <Handle type="target" :position="Position.Left" :id="`${id}-left-target`" />
                <Handle type="source" :position="Position.Right" :id="`${id}-right`" />
                <Handle type="target" :position="Position.Right" :id="`${id}-right-target`" />

                <div class="node-label" v-if="editingNodeId !== id">{{ data.label }}</div>
                <input
                  v-else
                  v-model="editingLabel"
                  @blur="() => finishEditLabel(id)"
                  @keyup.enter="() => finishEditLabel(id)"
                  @keyup.esc="cancelEditLabel"
                  class="node-label-input"
                  autofocus
                />
              </div>
            </template>
          </VueFlow>
        </div>
      </div>
      
      <template v-if="flowchart?.description" #footer>
        <div class="flowchart-description">
          {{ flowchart.description }}
        </div>
      </template>
    </n-card>
    
    <!-- 节点详情弹窗 -->
    <n-modal
      v-model:show="showNodeDetail"
      :mask-closable="true"
      preset="card"
      :style="{ width: isMobile ? '90%' : '600px' }"
      :title="`节点详情 - ${selectedNode?.data?.label || ''}`"
    >
      <div v-if="selectedNode" class="node-detail-content">
        <n-space vertical>
          <div>
            <strong>任务名称：</strong>
            <n-input
              v-if="isEditMode"
              v-model:value="selectedNode.data.label"
              placeholder="请输入任务名称"
              style="width: 100%"
            />
            <span v-else>{{ selectedNode.data.label }}</span>
          </div>
          <div>
            <strong>描述：</strong>
            <n-input
              v-if="isEditMode"
              v-model:value="selectedNode.data.description"
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 4 }"
              placeholder="请输入任务描述"
            />
            <span v-else>{{ selectedNode.data.description || '暂无描述' }}</span>
          </div>

          <n-divider />
          
          <div class="task-detail-section">
            <h4>任务详情</h4>
            <n-space vertical>
              <!-- 任务状态 -->
              <div>
                <strong>任务状态：</strong>
                <n-button
                  :type="getNodeStatus(selectedNode.id) === '已完成' ? 'success' : 'default'"
                  @click="toggleNodeStatus(selectedNode.id)"
                  size="small"
                >
                  {{ getNodeStatus(selectedNode.id) === '已完成' ? '已完成' : '未完成' }}
                </n-button>
              </div>

              <!-- 地图 -->
              <div>
                <strong>地图：</strong>
                <n-input
                  v-if="isEditMode"
                  v-model:value="selectedNode.data.map"
                  placeholder="例如：中央区域、工业区"
                  style="width: 100%"
                />
                <span v-else>{{ selectedNode.data.map || '未设置' }}</span>
              </div>

              <!-- 注意事项 -->
              <div>
                <strong>注意事项：</strong>
                <n-input
                  v-if="isEditMode"
                  v-model:value="selectedNode.data.notes"
                  type="textarea"
                  placeholder="请输入任务注意事项"
                  :autosize="{ minRows: 2, maxRows: 4 }"
                />
                <span v-else>{{ selectedNode.data.notes || '无' }}</span>
              </div>

              <!-- 任务条件 -->
              <div>
                <strong>任务条件：</strong>
                <div v-if="isEditMode" class="conditions-editor">
                  <div v-for="(condition, index) in selectedNode.data.conditions" :key="index" class="condition-item">
                    <n-input
                      v-model:value="selectedNode.data.conditions[index]"
                      :placeholder="`条件${index + 1}`"
                      style="flex: 1"
                    />
                    <n-button
                      v-if="selectedNode.data.conditions.length > 1"
                      @click="removeCondition(index)"
                      type="error"
                      size="small"
                      style="margin-left: 8px"
                    >
                      删除
                    </n-button>
                  </div>
                  <n-button
                    v-if="selectedNode.data.conditions.length < 10"
                    @click="addCondition"
                    secondary
                    size="small"
                    style="margin-top: 8px"
                  >
                    添加条件
                  </n-button>
                </div>
                <div v-else class="conditions-display">
                  <div v-for="(condition, index) in selectedNode.data.conditions.filter((c: string) => c.trim())" :key="index">
                    {{ index + 1 }}. {{ condition }}
                  </div>
                  <span v-if="selectedNode.data.conditions.filter((c: string) => c.trim()).length === 0">无条件</span>
                </div>
              </div>

              <!-- 任务奖励 -->
              <div>
                <strong>任务奖励：</strong>
                <div v-if="isEditMode" class="rewards-editor">
                  <n-space vertical>
                    <div class="reward-item">
                      <span class="reward-label">经验值：</span>
                      <n-input
                        v-model:value="selectedNode.data.rewards.experience"
                        placeholder="例如：1000"
                        style="width: 150px"
                      />
                    </div>
                    <div class="reward-item">
                      <span class="reward-label">物品：</span>
                      <n-input
                        v-model:value="selectedNode.data.rewards.items"
                        placeholder="例如：高级装备箱×1"
                        style="width: 200px"
                      />
                    </div>
                    <div class="reward-item">
                      <span class="reward-label">哈夫币：</span>
                      <n-input
                        v-model:value="selectedNode.data.rewards.huffCoins"
                        placeholder="例如：500"
                        style="width: 150px"
                      />
                    </div>
                  </n-space>
                </div>
                <div v-else class="rewards-display">
                  <div v-if="selectedNode.data.rewards.experience">经验值：{{ selectedNode.data.rewards.experience }}</div>
                  <div v-if="selectedNode.data.rewards.items">物品：{{ selectedNode.data.rewards.items }}</div>
                  <div v-if="selectedNode.data.rewards.huffCoins">哈夫币：{{ selectedNode.data.rewards.huffCoins }}</div>
                  <span v-if="!selectedNode.data.rewards.experience && !selectedNode.data.rewards.items && !selectedNode.data.rewards.huffCoins">无奖励</span>
                </div>
              </div>

              <!-- 编辑人 -->
              <div>
                <strong>编辑人：</strong>
                <n-input
                  v-if="isEditMode"
                  v-model:value="selectedNode.data.editor"
                  placeholder="请输入编辑人姓名"
                  style="width: 200px"
                />
                <span v-else>{{ selectedNode.data.editor || '未设置' }}</span>
              </div>
            </n-space>
          </div>
        </n-space>
      </div>
      
      <template #footer>
        <n-space justify="end">
          <n-button v-if="!isEditMode" @click="showNodeDetail = false">关闭</n-button>
          <template v-else>
            <n-button @click="cancelNodeEdit">取消</n-button>
            <n-button type="primary" @click="saveNodeDetails">保存</n-button>
          </template>
        </n-space>
      </template>
    </n-modal>

    <!-- 密码验证弹窗 -->
    <n-modal
      v-model:show="showPasswordDialog"
      :mask-closable="false"
      preset="dialog"
      title="编辑模式验证"
      positive-text="确认"
      negative-text="取消"
      :positive-button-props="{ loading: passwordVerifying }"
      @positive-click="verifyPasswordAndEnterEditMode"
      @negative-click="cancelPasswordVerification"
    >
      <div style="margin: 16px 0;">
        <p style="margin-bottom: 12px; color: var(--n-text-color-2);">
          请输入编辑模式密码以继续：
        </p>
        <n-input
          v-model:value="editPassword"
          type="password"
          placeholder="请输入密码"
          show-password-on="click"
          @keyup.enter="verifyPasswordAndEnterEditMode"
          :disabled="passwordVerifying"
        />
      </div>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { NCard, NSelect, NButton, NSpace, NSpin, NEmpty, NIcon, NDivider, NModal, NInput, useMessage } from 'naive-ui'
import { VueFlow, useVueFlow, Handle, Position, Connection, Edge, Node } from '@vue-flow/core'
import { Background } from '@vue-flow/background'
import '@vue-flow/core/dist/style.css'
import '@vue-flow/core/dist/theme-default.css'
import { getFlowchartList, updateFlowchart, verifyEditPassword } from '@/api/taskFlowchart'
import type { TaskFlowchart } from '@/api/taskFlowchart'
import { v4 as uuidv4 } from 'uuid'

const message = useMessage()
const { addNodes, addEdges, removeNodes, removeEdges } = useVueFlow()

// 状态
const loading = ref(false)
const saving = ref(false)
const flowcharts = ref<TaskFlowchart[]>([])
const flowchart = ref<TaskFlowchart | null>(null)
const selectedSeason = ref('S5')
const isEditMode = ref(false)

// Vue Flow 数据
const flowNodes = ref<Node[]>([])
const flowEdges = ref<Edge[]>([])

// 编辑相关
const editingNodeId = ref<string | null>(null)
const editingLabel = ref('')

// 窗口大小和响应式
const wrapperRef = ref<HTMLElement>()
const flowchartHeight = ref(600)
const isMobile = ref(false)

// 节点详情相关
const showNodeDetail = ref(false)
const selectedNode = ref<Node | null>(null)
const originalNodeData = ref<any>(null) // 备份原始数据

// 密码验证相关
const showPasswordDialog = ref(false)
const editPassword = ref('')
const passwordVerifying = ref(false)

// 本地任务状态存储
const localTaskStatus = ref<Record<string, Record<string, string>>>({})

// 任务状态选项 - 简化为只有两种状态
const taskStatusOptions = [
  { label: '未完成', value: '未完成' },
  { label: '已完成', value: '已完成' }
]

// 获取任务状态类型
function getTaskStatusType(status?: string): string {
  switch (status) {
    case '待开始': return 'default'
    case '进行中': return 'success'
    case '已完成': return 'info'
    case '已暂停': return 'warning'
    default: return 'default'
  }
}

// 从本地存储加载任务状态
function loadLocalTaskStatus() {
  const stored = localStorage.getItem('taskFlowchartStatus')
  if (stored) {
    localTaskStatus.value = JSON.parse(stored)
  }
}

// 保存任务状态到本地存储
function saveLocalTaskStatus() {
  localStorage.setItem('taskFlowchartStatus', JSON.stringify(localTaskStatus.value))
}

// 获取节点的任务状态
function getNodeStatus(nodeId: string): string {
  const seasonStatus = localTaskStatus.value[selectedSeason.value] || {}
  return seasonStatus[nodeId] || '未完成'
}

// 设置节点的任务状态
function setNodeStatus(nodeId: string, status: string) {
  if (!localTaskStatus.value[selectedSeason.value]) {
    localTaskStatus.value[selectedSeason.value] = {}
  }
  localTaskStatus.value[selectedSeason.value][nodeId] = status

  // 如果标记为完成，检查并更新前置任务
  if (status === '已完成') {
    updatePreviousNodesStatus(nodeId)
  }

  saveLocalTaskStatus()
}

// 切换节点状态（在已完成和未完成之间切换）
function toggleNodeStatus(nodeId: string) {
  const currentStatus = getNodeStatus(nodeId)
  const newStatus = currentStatus === '已完成' ? '未完成' : '已完成'
  setNodeStatus(nodeId, newStatus)
}

// 更新前置节点的状态
function updatePreviousNodesStatus(completedNodeId: string) {
  // 找到所有指向已完成节点的边
  const incomingEdges = flowEdges.value.filter(edge => edge.target === completedNodeId)
  
  // 递归更新所有前置节点
  incomingEdges.forEach(edge => {
    const previousNodeId = edge.source
    const currentStatus = getNodeStatus(previousNodeId)
    
    // 如果前置节点还未完成，将其标记为完成
    if (currentStatus !== '已完成') {
      setNodeStatus(previousNodeId, '已完成')
    }
  })
}

// 监听窗口大小变化
const checkMobile = () => {
  isMobile.value = window.innerWidth <= 768
}

const updateFlowchartHeight = () => {
  nextTick(() => {
    if (wrapperRef.value) {
      // 获取wrapper元素的位置
      const rect = wrapperRef.value.getBoundingClientRect()
      // 计算从wrapper顶部到窗口底部的可用高度
      const availableHeight = window.innerHeight - rect.top
      
      // 设置高度，确保填满剩余空间
      flowchartHeight.value = Math.max(400, availableHeight)
    }
  })
}

// 计算流程图样式
const flowchartStyle = computed(() => ({
  height: `${flowchartHeight.value}px`
}))

// 计算属性
const seasonOptions = computed(() => {
  return ['S5', 'S4', 'S3', 'S2', 'S1'].map(s => ({
    label: `第${s.slice(1)}赛季`,
    value: s
  }))
})

// 加载流程图列表
async function loadFlowcharts() {
  loading.value = true
  try {
    const res = await getFlowchartList({ status: 'active' })
    if (res.code === 1) {
      // 处理数据，确保 nodes_data 和 edges_data 是数组
      flowcharts.value = res.data.list.map(chart => ({
        ...chart,
        nodes_data: typeof chart.nodes_data === 'string' 
          ? JSON.parse(chart.nodes_data || '[]') 
          : chart.nodes_data || [],
        edges_data: typeof chart.edges_data === 'string' 
          ? JSON.parse(chart.edges_data || '[]') 
          : chart.edges_data || []
      }))
      
      // 自动加载当前赛季的流程图
      const currentSeasonChart = flowcharts.value.find(f => f.season === selectedSeason.value)
      if (currentSeasonChart) {
        loadFlowchart(currentSeasonChart)
      }
    }
  } catch (error) {
    console.error('加载流程图失败:', error)
    message.error('加载流程图失败')
  } finally {
    loading.value = false
  }
}

// 加载流程图数据到 Vue Flow
function loadFlowchart(chart: TaskFlowchart) {
  flowchart.value = chart

  // 转换节点数据，确保数据结构兼容性
  flowNodes.value = chart.nodes_data.map(node => {
    // 兼容旧数据结构，确保新字段存在
    const nodeData = {
      label: node.label || node.data?.label || '新节点',
      description: node.data?.description || '',
      map: node.data?.map || '',
      notes: node.data?.notes || '',
      conditions: node.data?.conditions || [''],
      rewards: node.data?.rewards || {
        experience: '',
        items: '',
        huffCoins: ''
      },
      editor: node.data?.editor || ''
    }

    return {
      id: node.id,
      type: node.type,
      position: node.position,
      data: nodeData
    }
  })

  // 转换边数据
  flowEdges.value = chart.edges_data.map(edge => ({
    id: edge.id,
    source: edge.source,
    target: edge.target,
    label: edge.label,
    type: edge.type || 'default',
    animated: edge.type === 'animated',
    style: edge.style
  }))

  // 加载流程图后更新高度
  nextTick(() => {
    updateFlowchartHeight()
  })
}

// 切换赛季
function handleSeasonChange(season: string) {
  const chart = flowcharts.value.find(f => f.season === season)
  if (chart) {
    loadFlowchart(chart)
  } else {
    flowchart.value = null
    flowNodes.value = []
    flowEdges.value = []
  }
  isEditMode.value = false
}

// 启用编辑模式 - 需要密码验证
function enableEditMode() {
  editPassword.value = ''
  showPasswordDialog.value = true
}

// 验证密码并进入编辑模式
async function verifyPasswordAndEnterEditMode() {
  if (!editPassword.value.trim()) {
    message.error('请输入密码')
    return
  }

  passwordVerifying.value = true
  try {
    const response = await verifyEditPassword(editPassword.value)
    if (response.data.valid) {
      isEditMode.value = true
      showPasswordDialog.value = false
      editPassword.value = ''
      message.success('已进入编辑模式')
    } else {
      message.error('密码错误，无法进入编辑模式')
    }
  } catch (error) {
    console.error('密码验证失败:', error)
    message.error('密码验证失败，请重试')
  } finally {
    passwordVerifying.value = false
  }
}

// 取消密码验证
function cancelPasswordVerification() {
  showPasswordDialog.value = false
  editPassword.value = ''
}

// 添加节点 - 简化为统一的默认节点
function addNode(type: string = 'task') {
  const newNode: Node = {
    id: uuidv4(),
    type: 'task', // 统一使用 task 类型
    position: {
      x: Math.random() * 500 + 100,
      y: Math.random() * 300 + 100
    },
    data: {
      label: '新节点',
      description: '',
      map: '',
      notes: '',
      conditions: [''],
      rewards: {
        experience: '',
        items: '',
        huffCoins: ''
      },
      editor: ''
    }
  }

  addNodes([newNode])
}

// 连接事件
function onConnect(params: Connection) {
  if (!params.source || !params.target) return

  const newEdge: Edge = {
    id: `edge-${uuidv4()}`,
    source: params.source,
    target: params.target,
    sourceHandle: params.sourceHandle,
    targetHandle: params.targetHandle,
    type: 'default',
    animated: false
  }

  addEdges([newEdge])
}

// 节点变化
function onNodesChange() {
  // Vue Flow 会自动处理节点的变化
}

// 边变化
function onEdgesChange() {
  // Vue Flow 会自动处理边的变化
}

// 清空画布
function clearAll() {
  flowNodes.value = []
  flowEdges.value = []
  message.info('画布已清空')
}

// 保存流程图
async function handleSave() {
  if (!flowchart.value) return

  saving.value = true
  try {
    // 转换回原始格式
    const nodes_data = flowNodes.value.map(node => ({
      id: node.id,
      type: node.type || 'task',
      label: node.data.label,
      position: node.position,
      data: node.data
    }))

    const edges_data = flowEdges.value.map(edge => ({
      id: edge.id,
      source: edge.source,
      target: edge.target,
      label: typeof edge.label === 'string' ? edge.label : '',
      type: edge.type || 'default',
      style: edge.style
    }))

    await updateFlowchart({
      id: flowchart.value.id,
      nodes_data,
      edges_data
    })

    message.success('保存成功')
    isEditMode.value = false
  } catch (error) {
    message.error('保存失败')
  } finally {
    saving.value = false
  }
}

// 取消编辑
function handleCancel() {
  isEditMode.value = false
  // 重新加载数据以恢复原始状态
  if (flowchart.value) {
    loadFlowchart(flowchart.value)
  }
}

// 开始编辑标签
function startEditLabel(nodeId: string) {
  if (!isEditMode.value) return
  
  const node = flowNodes.value.find(n => n.id === nodeId)
  if (node) {
    editingNodeId.value = nodeId
    editingLabel.value = node.data.label
  }
}

// 完成编辑标签
function finishEditLabel(nodeId: string) {
  const node = flowNodes.value.find(n => n.id === nodeId)
  if (node && editingLabel.value.trim()) {
    node.data.label = editingLabel.value.trim()
  }
  editingNodeId.value = null
  editingLabel.value = ''
}

// 取消编辑标签
function cancelEditLabel() {
  editingNodeId.value = null
  editingLabel.value = ''
}

// 节点点击事件
function onNodeClick({ node }: { node: Node }) {
  // 确保节点数据结构完整，兼容旧数据
  const nodeData = {
    label: node.data.label || '新节点',
    description: node.data.description || '',
    map: node.data.map || '',
    notes: node.data.notes || '',
    conditions: node.data.conditions || [''],
    rewards: node.data.rewards || {
      experience: '',
      items: '',
      huffCoins: ''
    },
    editor: node.data.editor || ''
  }

  // 显示节点详情，备份原始数据
  selectedNode.value = { ...node, data: { ...nodeData } } // 深拷贝避免直接修改原数据
  originalNodeData.value = { ...nodeData } // 备份原始数据
  showNodeDetail.value = true
}



// 保存节点详情
function saveNodeDetails() {
  if (selectedNode.value) {
    // 找到原始节点并更新数据
    const nodeIndex = flowNodes.value.findIndex(n => n.id === selectedNode.value!.id)
    if (nodeIndex !== -1) {
      flowNodes.value[nodeIndex].data = { ...selectedNode.value.data }
      message.success('节点详情已保存')
    }
    showNodeDetail.value = false
  }
}

// 取消编辑节点详情
function cancelNodeEdit() {
  if (selectedNode.value && originalNodeData.value) {
    // 恢复原始数据
    selectedNode.value.data = { ...originalNodeData.value }
  }
  showNodeDetail.value = false
}



// 添加任务条件
function addCondition() {
  if (selectedNode.value && selectedNode.value.data.conditions.length < 10) {
    selectedNode.value.data.conditions.push('')
  }
}

// 删除任务条件
function removeCondition(index: number) {
  if (selectedNode.value && selectedNode.value.data.conditions.length > 1) {
    selectedNode.value.data.conditions.splice(index, 1)
  }
}

// 组件挂载
onMounted(() => {
  loadFlowcharts()
  loadLocalTaskStatus()
  checkMobile()
  updateFlowchartHeight()
  
  window.addEventListener('resize', handleResize)
})

// 组件卸载
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})

// 处理窗口大小变化
function handleResize() {
  checkMobile()
  updateFlowchartHeight()
}
</script>

<style scoped>
.task-flowchart-container {
  height: calc(100vh - 72px); /* 减去顶部导航栏高度 72px */
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.task-flowchart-container > .n-card {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  border-radius: 0;
  border: none;
}

:deep(.n-card__content) {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  padding: 0;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 20px;
}

.header-content h2 {
  margin: 0;
}

.flowchart-wrapper {
  position: relative;
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.flowchart-content {
  position: relative;
  flex: 1;
  overflow: hidden;
}

.edit-toolbar {
  position: absolute;
  top: 10px;
  left: 50%;
  transform: translateX(-50%);
  background: white;
  padding: 8px 16px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 100;
  max-width: 90%;
  overflow-x: auto;
}

.edit-toolbar.mobile {
  left: 10px;
  right: 10px;
  transform: none;
  padding: 4px 8px;
}

.edit-toolbar.mobile .n-button {
  font-size: 12px;
  padding: 0 8px;
}

@media (max-width: 768px) {
  .task-flowchart-container {
    height: calc(100vh - 72px); /* 移动端导航栏高度 */
  }
  
  .header-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .header-content h2 {
    font-size: 18px;
  }
  
  .edit-toolbar .n-space {
    flex-wrap: wrap;
  }
  
  .vue-flow-container {
    touch-action: none;
  }
  
  :deep(.vue-flow__controls) {
    bottom: 10px;
    right: 10px;
    scale: 0.8;
  }
  
  :deep(.vue-flow__minimap) {
    display: none;
  }
  
  :deep(.n-card__content) {
    padding: 0 !important;
  }
}

.loading-overlay {
  position: absolute;
  inset: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.8);
  z-index: 10;
}

.empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  min-height: 400px;
}


.edit-toolbar {
  position: absolute;
  top: 10px;
  left: 50%;
  transform: translateX(-50%);
  background: var(--n-card-color, #ffffff);
  padding: 8px 16px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: 1px solid var(--n-border-color, #e0e0e0);
  z-index: 100;
}

.edit-tips {
  font-size: 12px;
  color: var(--n-text-color-2, #666666);
  margin: 0 8px;
}

/* 深色模式下的编辑工具栏 */
html.dark .edit-toolbar {
  background: var(--n-card-color, #2d2d30);
  border-color: var(--n-border-color, #484848);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
}

html.dark .edit-tips {
  color: var(--n-text-color-2, #cccccc);
}

.vue-flow-container {
  width: 100%;
  height: 100%;
  background: #fafafa;
}

/* 深色模式下的画布背景 */
html.dark .vue-flow-container {
  background: #1a1a1a;
}

/* 自定义节点样式 */
.custom-node {
  padding: 10px 20px;
  border-radius: 8px;
  border: 2px solid var(--n-border-color, #999999);
  background: var(--n-card-color, #ffffff);
  min-width: 150px;
  text-align: center;
  transition: all 0.3s;
  position: relative;
}

.custom-node:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 节点状态指示器 */
.node-status-indicator {
  position: absolute;
  top: -8px;
  right: -8px;
  width: 16px;
  height: 16px;
  border-radius: 50%;
  border: 2px solid var(--n-card-color, #ffffff);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.status-未完成 {
  background-color: #d3d3d3;
}

.status-已完成 {
  background-color: #18a058;
}

/* 已完成节点的样式 - 移除透明度和虚线，改为颜色区分 */
.node-completed {
  /* 通过颜色来区分已完成状态，具体样式在 .node-completed.node-task 中定义 */
  position: relative;
}

.node-label {
  font-size: 14px;
  font-weight: 500;
  color: var(--n-text-color, #333333);
}

/* 深色模式下的节点标签 */
html.dark .node-label {
  color: var(--n-text-color, #ffffff);
}

/* 节点样式 - 统一的默认样式 */
.node-task {
  border-color: var(--n-border-color, #999999);
  background: var(--n-card-color, #ffffff);
}

/* 已完成节点的特殊样式 - 只有完成状态才有颜色区分 */
.node-completed.node-task {
  border-color: #18a058;
  background: #f0f9ff;
  box-shadow: 0 2px 8px rgba(24, 160, 88, 0.2);
}

/* 深色模式下的节点样式 */
html.dark .custom-node {
  border-color: var(--n-border-color, #666666);
  background: var(--n-card-color, #2d2d30);
}

html.dark .node-task {
  border-color: var(--n-border-color, #666666);
  background: var(--n-card-color, #2d2d30);
}

/* 深色模式下的已完成节点 */
html.dark .node-completed.node-task {
  border-color: #18a058;
  background: #1a3a2e;
  box-shadow: 0 2px 8px rgba(24, 160, 88, 0.3);
}

.node-label-input {
  width: 100%;
  border: 1px solid #2080f0;
  border-radius: 4px;
  padding: 2px 8px;
  font-size: 14px;
  font-weight: 500;
  text-align: center;
  outline: none;
  background: white;
}

.flowchart-description {
  color: #666;
  font-size: 14px;
  line-height: 1.6;
}

/* Vue Flow 控件样式调整 */
:deep(.vue-flow__controls) {
  bottom: 20px;
  right: 20px;
}

:deep(.vue-flow__minimap) {
  bottom: 20px;
  right: 100px;
}

/* Handle 样式 */
:deep(.vue-flow__handle) {
  width: 12px;
  height: 12px;
  background: #2080f0;
  border: 2px solid white;
}

:deep(.vue-flow__handle:hover) {
  width: 16px;
  height: 16px;
}

/* 边的样式 */
:deep(.vue-flow__edge-path) {
  stroke-width: 3px !important;
  stroke: #666 !important;
}

:deep(.vue-flow__edge.selected .vue-flow__edge-path) {
  stroke: #2080f0 !important;
  stroke-width: 4px !important;
}

:deep(.vue-flow__edge:hover .vue-flow__edge-path) {
  stroke: #2080f0 !important;
  stroke-width: 4px !important;
}

/* 边的标签样式 */
:deep(.vue-flow__edge-label) {
  background: white;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
  border: 1px solid #ddd;
}

/* 节点详情样式 */
.node-detail-content {
  padding: 10px 0;
}

.task-detail-section {
  margin-top: 20px;
}

.task-detail-section h4 {
  margin-bottom: 15px;
  color: var(--n-text-color, #333333);
}

.task-detail-section strong {
  color: var(--n-text-color, #333333);
}

.task-detail-section span {
  color: var(--n-text-color-2, #666666);
}

.task-detail-section .n-input,
.task-detail-section .n-select {
  margin-top: 5px;
}

/* 深色模式下的任务详情 */
html.dark .task-detail-section h4 {
  color: var(--n-text-color, #ffffff);
}

html.dark .task-detail-section strong {
  color: var(--n-text-color, #ffffff);
}

html.dark .task-detail-section span {
  color: var(--n-text-color-2, #cccccc);
}

/* 条件编辑器样式 */
.conditions-editor {
  margin-top: 8px;
}

.condition-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.conditions-display {
  margin-top: 8px;
  padding-left: 16px;
}

.conditions-display div {
  margin-bottom: 4px;
  color: var(--n-text-color-2, #666666);
}

/* 奖励编辑器样式 */
.rewards-editor {
  margin-top: 8px;
}

.reward-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.reward-label {
  min-width: 60px;
  color: var(--n-text-color, #333333);
  font-weight: 500;
}

.rewards-display {
  margin-top: 8px;
  padding-left: 16px;
}

.rewards-display div {
  margin-bottom: 4px;
  color: var(--n-text-color-2, #666666);
}

/* 深色模式下的新样式 */
html.dark .conditions-display div {
  color: var(--n-text-color-2, #cccccc);
}

html.dark .reward-label {
  color: var(--n-text-color, #ffffff);
}

html.dark .rewards-display div {
  color: var(--n-text-color-2, #cccccc);
}
</style>